// 政采云供应商管理服务
'use strict';

const Service = require('egg').Service;
const { Op } = require('sequelize');

class SupplierService extends Service {
  async createSupplier(params) {
    return this.ctx.model.Supplier.transaction(async t => {
      // 国密加密统一社会信用代码
      const encryptedCreditCode = this.ctx.service.zcyCrypto.encryptSM4(
        params.creditCode,
        this.config.zcy.sm4Key
      );

      const supplier = await this.ctx.model.Supplier.create({
        ...params,
        provinceCode: this.ctx.state.user.provinceCode,
        creditCode: encryptedCreditCode,
        status: 'pending'
      }, { transaction: t });

      // 区块链存证
      await this.ctx.service.blockchain.record({
        action: 'SUPPLIER_CREATE',
        data: supplier
      });

      return supplier;
    });
  }

  // 供应商风险评估
  async evaluateRisk(supplierId) {
    const [financials, orders] = await Promise.all([
      this.ctx.model.SupplierFinancial.findAll({
        where: { supplierId }
      }),
      this.ctx.model.Order.findAll({
        where: { supplierId }
      })
    ]);

    // 使用阿里云风险模型计算
    return this.ctx.curl(`${this.config.riskEngine}/evaluate`, {
      method: 'POST',
      dataType: 'json',
      data: {
        financials,
        orderStats: this._calculateOrderStats(orders)
      }
    });
  }

  _calculateOrderStats(orders) {
    // 实现订单统计逻辑...
  }
}

module.exports = SupplierService;